
const db = require('db');
const getAccessToken = require('tools/dd/getAccessToken');
const getUserInfo = require('tools/dd/getUserInfo');
const { toUpdate } = require('tools/sqlString');

module.exports = async ctx => {
    const { connection, run } = db.init();
    await run('BEGIN'); // 开始事务
    try {
        const id = ctx.params.id;
        const body = ctx.request.body;
        const company = ctx.headers["company-id"];
        const access_token = await getAccessToken(company);
        const user = await getUserInfo(access_token, body.pmId);
        await update(id, {
            ...body,
            pmEmail: user.email || 'null',
            orderStatus: '等待制作',
            deptId: 'null',
            deptName: 'null',
            startTime: 'null',
            completionTime: 'null',
        }, run);
        await delSettlementEntry(id, run);
        await run('COMMIT');
        ctx.status = 200;
        ctx.body = 'ok';
    } catch (error) {
        await run('ROLLBACK');
        ctx.status = 500;
        ctx.body = error
    }
    connection.end();
}

// 更先进数据
async function update(id, body, run) {
    const sql = toSqlString(id, body);
    const result = await run(sql);
    if (result.err) {
        throw result.err
    }
}

// 删除结算条目
async  function delSettlementEntry(id, run) {
    const sql = `DELETE FROM settlementEntry WHERE ordersId=${id}`
    const result = await run(sql);
    if (result.err) {
        throw result.err
    }
}

function toSqlString(id, body) {
    const sql = `
        UPDATE orders SET ${toUpdate(body)}
        WHERE id = ${id}
    `;
    return sql;
}